﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Clotho.Novelview;
using Clotho.UI;

namespace Clotho {
	public partial class MainForm : Form {
		public readonly Novel Nov ;
		/// <summary>
		/// 用来打开引导界面
		/// </summary>
		public readonly UI.Guide guild_form;


		public MainForm() {
			InitializeComponent();
		}

		public MainForm(Guide guild_form, string open_path = null) {
			InitializeComponent();
			this.guild_form = guild_form;
			if (open_path != null) {
				Nov = Novel.open(open_path);
				UI.AllViews.injectTo(Nov.Topic_Control_keeps, Nov, showControl);
				Nov.File_path = open_path;
				try {
					lordFormInfo(getStudioPathName());
				} catch(Exception e){
					MessageBox.Show("恢复上次的布局失败。");
				}
			} else {
				Nov = Novel.create();
				UI.AllViews.injectTo(Nov.Topic_Control_keeps, Nov, showControl);
				showNovelView();
			}
			Nov.eAddContolKeeper += Nov_eAddContolKeeper;

		}

		private void Nov_eAddContolKeeper(object sender, TEventArgs<ControlKeeper> e) {
			mainStudio.addControl(e.Value.Control);

		}

		private void showNovelView() {
			mainStudio.Split(MutFormStudio.SplitDirection.Right);
			mainStudio.Second_studio.Split(MutFormStudio.SplitDirection.Bottom);
			mainStudio.addControl(Nov.Ui_control_enumable.First(ck => ck.Head_text == "主线剧情").Control);
			mainStudio.Second_studio.addControl(Nov.Ui_control_enumable.First(ck => ck.Head_text == "全部情节").Control);
			mainStudio.Second_studio.Second_studio.addControl(Nov.Ui_control_enumable.First(ck => ck.Head_text == "故事总览").Control);
			mainStudio.Splitter.FixedPanel = FixedPanel.Panel2;
			WindowState = FormWindowState.Maximized;

		}

		private static System.Xml.XmlWriterSettings xml_setting = new System.Xml.XmlWriterSettings() {
			Indent = true,
			OmitXmlDeclaration = false,
			Encoding = Encoding.UTF8,
		};
		private void storeFormInfo(string Stuido_xaml_file_path) {
			MutFormStudio.ToXaml.Studio studio_xaml_obj = mainStudio.ToXaml();
			studio_xaml_obj.Sub_studios[0].Form = new MutFormStudio.ToXaml.Form(this);
			using (var xml = System.Xml.XmlWriter.Create(Stuido_xaml_file_path,xml_setting)) {
				System.Windows.Markup.XamlWriter.Save(studio_xaml_obj, xml);
				xml.Flush();
			}
		}

		private void lordFormInfo(string Stuido_xaml_file_path) {
			System.IO.Stream rs = System.IO.File.OpenRead(Stuido_xaml_file_path);
			MutFormStudio.ToXaml.Studio studio_xaml_obj =( System.Windows.Markup.XamlReader.Load(rs) as MutFormStudio.ToXaml.Studio);
			studio_xaml_obj.Sub_studios[0].Form.setToForm(this);
			mainStudio.loadByXaml(studio_xaml_obj, createControl);
		}

		private Control createControl(string arg) {
			UI.ControlKeeper control_keeper = Nov.Ui_control_enumable.First(ck => ck.Create_string == arg);
			return control_keeper.Control;
		}
		private void showControl(ControlKeeper ck) {
			var ctrl = ck.Control;
			if (ctrl.TopLevelControl == null) {
				mainStudio.addControl(ctrl);
			} else {
				mainStudio.TopMostControl(ctrl);
			}
		}



		private void 保存ToolStripMenuItem_Click(object sender, EventArgs e) {
			if(Nov.File_path != null) {
				Nov.save(Nov.File_path);
			} else {
				另存为ToolStripMenuItem_Click(sender, e);
			}
		}
		private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e) {
			mainSAVE.FileName = Nov.File_path;
			mainSAVE.ShowDialog();
		}
		private void mainSAVE_FileOk(object sender, CancelEventArgs e) {
			Nov?.save(mainSAVE.FileName);
			Nov.File_path = mainSAVE.FileName;
		}
		private void 撤销ToolStripMenuItem_Click(object sender, EventArgs e) {
			Nov?.undo();
		}
		private void 重做ToolStripMenuItem_Click(object sender, EventArgs e) {
			Nov?.redo();
		}

		private void 关闭ToolStripMenuItem_Click(object sender, EventArgs e) {

		}
		string getStudioPathName() {
			if (Nov == null) {
				return null;
			}
			if (Nov.File_path == null) {
				return null;
			}
			return System.IO.Path.ChangeExtension(Nov.File_path,".布局.xml");

		}

		private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
			if(Nov.Is_modifyed == true) {
				var result = MessageBox.Show("即将关闭还未保存的作品，是否先进行保存？", "正在关闭", MessageBoxButtons.YesNoCancel);
				if(result == DialogResult.Yes) {
					保存ToolStripMenuItem_Click(sender,e);
				}else if(result == DialogResult.Cancel) {
					e.Cancel = true;
					return;
				}
			}
			var Stuido_xaml_file_path = getStudioPathName();
			if (Stuido_xaml_file_path != null) {
				storeFormInfo(Stuido_xaml_file_path);
			}
			return;
		}

		private void 打开故事总览ToolStripMenuItem_Click(object sender, EventArgs e) {
			var ctrl = createControl("故事总览");
			if(ctrl.TopLevelControl == null) {
				mainStudio.addControl(ctrl);
			}
		}
		
		private void 添加故事线ToolStripMenuItem_Click(object sender, EventArgs e) {
			Nov.createStoreLine();
			
		}

		private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) {
			Plot[] selectedPlots = (from plot in Nov 
								where plot.Selected
								select plot).ToArray();
			if (selectedPlots.Length == 0) {
				return;
			} else {
				Nov.addCmdKnot();
				Nov.doCmd(
					() => {
						foreach (Plot p in selectedPlots) {
							Nov.removePlot(p);
						}
					},
					()=> {
						foreach (Plot p in selectedPlots) {
							Nov.addPlot(p);
						}
					}
				);
			}


		}
	}
}
